package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"study/md5test/md5t"
	"sync"
	"time"
)

func GetCurrentPath() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	path = string(path[0:strings.LastIndex(path, "\\")])
	return path
}
func Test2() {
	fm := md5t.New()
	//fm.FMsg("E:\\Soft")
	fm.FMsg("E:\\assets\\hnupl\\dealer")
	fileName := fmt.Sprint(GetCurrentPath(), "\\log\\test2log", strconv.Itoa(int(time.Now().Unix())), ".log")
	fmt.Println(fileName)
	logFile, logErr := os.Create(fileName)
	if logErr != nil {
		fmt.Println(logErr)
	} else {
		defer logFile.Close()
		for i, v := range fm.FileNames {
			ftime := time.Now().Unix()
			file, err := os.Open(v)
			if err != nil {
				fmt.Println(i, "error=", err)
			}

			md5s, err := md5t.GetFileMd5(file, 1024)
			file.Close()
			ltime := time.Now().Unix()
			logs := fmt.Sprint("Test2 第 ", i+1, " 个文件 Md5值= ", md5s, "\t", v, "\t", err, "\t用时", (ltime - ftime), "\r")
			fmt.Println(logs)
			logFile.WriteString(logs)
		}
	}
}

//使用goroutine 多任务读取文件
func Test1() {
	fm := md5t.New()
	//fm.FMsg("E:\\Soft")
	fm.FMsg("E:\\assets\\hnupl\\dealer")
	fileName := fmt.Sprint(GetCurrentPath(), "\\log\\test1log", strconv.Itoa(int(time.Now().Unix())), ".log")
	fmt.Println(fileName)
	logFile, logErr := os.Create(fileName)
	if logErr != nil {
		fmt.Println(logErr)
	} else {
		maxSize := 1024 * 10000 //文件分隔按该数字拆分
		defer logFile.Close()
		for i, v := range fm.FileNames {
			ftime := time.Now().Unix()
			file, err := os.Open(v)
			if err != nil {
				fmt.Println(i, "error=", err)
			}

			m := md5.New()
			swg := sync.WaitGroup{}
			stat, err := file.Stat()
			//fmt.Println("size=", stat.Size(), err)
			num := (int(stat.Size()) + maxSize) / maxSize //拆分文件获得线程数
			//fmt.Println("num=", num)
			swg.Add(num)
			for i := 0; i < num; i++ {
				go func() {
					err := md5t.Test(m, file, maxSize*(i+1), 10240)
					if err != nil {
						fmt.Println(err)
					}
					swg.Done()
				}()
			}
			swg.Wait()
			ltime := time.Now().Unix()
			//输出md5值
			md5s := hex.EncodeToString(m.Sum(nil))
			logs := fmt.Sprint("Test1 第 ", i+1, " 个文件 Md5值= ", md5s, "\t", v, "\t", err, "\t用时", (ltime - ftime), "\r")
			fmt.Println(logs)
			logFile.WriteString(logs)
			file.Close()
		}
	}
}
func main() {
	Test1()
	Test2()
}
